#include "../include/head.h"
int main(int argc, char *argv[]){
    ARGS_CHECK(argc,3);
    int sock = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sock,-1,"socket");
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(sock,(struct sockaddr*)&addr,sizeof(addr));
    ERROR_CHECK(ret,-1,"connect");
    char buf[1024];
    train_t train;

    int epfd=epoll_create(1);
    struct epoll_event ev;
    ev.events=EPOLLIN;
    ev.data.fd=STDIN_FILENO;

    epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&ev);
    ev.events=EPOLLIN;
    ev.data.fd=sock;
    epoll_ctl(epfd,EPOLL_CTL_ADD,sock,&ev);
    struct epoll_event readyset[1];

    while(1){
        int ret = login(sock);

        if(ret == 0){
            printf("client login ...\n");
            break;
        }
    }

    // 清空输入缓冲区
    int c;
    while ((c = getchar()) != '\n' && c != EOF);

    //fflush(stdout);
    while(1){
        epoll_wait(epfd,readyset,1,-1);


        if(readyset[0].data.fd == STDIN_FILENO){
            memset(&train, 0, sizeof(train));
            char *str;
            str=fgets(buf,sizeof(buf),stdin);
            printf("str1 == %s\n",str);
            str[strcspn(str, "\n")] = '\0';
            printf("str2 == %s\n",str);
            char data[1024];

            train.tag=mystrtok(str,data);
            printf("OP = %d \n",train.tag);
            strncpy(train.data,data,strlen(data));
            printf("msg = %s \n",train.data);
            train.length=strlen(data);
            send(sock,&train.tag,sizeof(int),0);
            printf("train.length = %d\n",train.length);
            send(sock,&train.length,sizeof(train.length),0);
            send(sock,train.data,train.length,0);
            if(train.tag==OP_PUTS){ 
                char filename[128];
                get_last_segment(train.data,filename);
                printf("put filename = %s\n",filename);
                cli_upload(sock,filename); 
            }else if(train.tag==OP_GETS){ 
                char filename[128];
                get_last_segment(train.data,filename); 
                printf("get last segment filename=%s\n",filename);
                download(sock,filename); 
            } 
        }else if(readyset[0].data.fd == sock){
            memset(&train, 0, sizeof(train));
            ssize_t sret= recv(sock,&train.tag,sizeof(int),0);

            if(sret == 0){
                printf("sret=0\n");
                break;
            }
            recv(sock,&train.length,sizeof(int),0);
            recv(sock,train.data,train.length,0);
            printf("%s\n",train.data);




        }
    }
    close(sock);

    return 0;
}

